package upload

import (
	"common/kms"
	"common/log"
	"context"
	"euplink"
	"euplink/config"
	"fmt"
	"go.uber.org/zap"
	"io"
	"sync"
	"time"
)

var proj *euplink.Project = nil
var gConfig config.Config
var glog *zap.Logger = nil
var once sync.Once

func initInter(apkeyString string) int {
	var err error
	fmt.Println("apkeyString", apkeyString)
	ctx := context.Background()
	gConfig = config.Config{
		CenterUrl:  "estore.guanjieai.com:10000",
		Timeout:    time.Minute * 10,
		P2PTimeout: time.Second * 20,
		Parallel:   true,
		MaxSegment: 60000000,
		UseP2P:     true,
		UseKms:     false,
		Kms: kms.Config{
			BaseUrl:            "https://47.106.76.249:9000",
			AppId:              "f12ce38f-069b-4cbd-9ba1-ee4846200fea",
			AppKey:             "wevKrmDsxu9v9CEFevNbRDxjYP2AP3ig",
			Timeout:            time.Second * 30,
			InsecureSkipVerify: true,
		},
		DefaultBucket: "default",
		ApiKey:        apkeyString,
		DebugDevice:   "",
	}
	logCfg := log.Config{
		File:        "",
		FileSize:    10,
		FileBackups: 10,
		FileAge:     30,
		Level:       "debug",
		Output:      "any",
		Encoder:     "console",
	}
	zapLog := log.NewZapLog(&logCfg)
	glog = zapLog

	proj, err = euplink.NewProject(ctx, gConfig, zapLog)
	if err != nil {
		fmt.Println("error NewProject", err)
		return -1
	}
	fmt.Println("init ok")
	return 0
}

func Init(apkeyString string) int {
	var ret = 0
	once.Do(func() {
		ret = initInter(apkeyString)
	})
	return ret
}

func UploadFile(key string, inFile io.Reader, size int64) int {
	ctx := context.Background()
	err := proj.UploadObject(ctx, gConfig.DefaultBucket, key, inFile, false, size, nil)
	if err != nil {
		glog.Error("UploadFile", zap.Error(err))
		return -1
	}
	return 0
}
